<template>
  <el-container>
    <el-main>
      <el-form ref="payable" :model="form"  label-width="90px">
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">收款信息</span>
        </div>
        <div style="display: flex">
          <el-form-item label="客户名称"  prop="memberId">
            <el-select  style="width: 201px" v-model="memberName"  value-key="id"  :filter-method="remoteMethod"  filterable placeholder="请选择客户" @change="selectMember">
              <el-option
                v-for="item in memberList"
                :key="item.id"
                :label="item.name"
                style="width: 600px"
                :value="item">
                <div style="display: flex">
                  <span style="float: left;width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.name }}</span>
                  <span style="width: 100px;overflow: hidden;text-overflow: ellipsis;">{{ item.phone }}</span>
                  <div style="width: 200px;">
                    <span style="color: #8492a6; font-size: 8px;">{{item.areaName}}{{item.address}}</span>
                  </div>
                </div>
              </el-option>
              <div style="display: flex;width: 100%;position: absolute;bottom: 0">
                <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                <div class="elOption" @click="toSearchMember">搜索客户</div>
              </div>
              <div style="height: 30px"></div>
            </el-select>
          </el-form-item>
          <!--<el-form-item label="对账单:">-->
            <!--<el-input v-model="form.sn" style="width: 201px" suffix-icon="el-icon-arrow-down" @focus="verifyDialogShow"/>-->
          <!--</el-form-item>-->
        </div>
        <div style="display: flex">
          <el-form-item label="支付方式:">
            <el-select style="width: 200px;" v-model="paymentPluginName" placeholder="请选择支付方式" @change="paymentChange">
              <el-option v-if="(isWaterShow==true && item.value == 'paperPayPlugin') || item.value != 'paperPayPlugin'" v-for="item in paymentOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
           <el-form-item label="收款人:">
            <el-select v-model="form.managerId" placeholder="请选择">
            <el-option
              v-for="item in sysEmployeelistobtain"
              :key="item.id"
              :label="item.name"
              :value="item.id">
           </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收款金额:">
            <el-input style="width: 200px;" v-model="collectAmount" type="number" placeholder="收款总金额" @change="collectAmountInput()">
              <el-button slot="append" @click="collectAmountInput()">开始冲账</el-button>
            </el-input>
          </el-form-item >

        </div>

        <div class="product_header_name" style="">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">应收款明细</span>
        </div>
        <el-table
          ref="receivableMemberTable"
          :data="receivableMemberList"
          :height="'46vh'"
          :summary-method="getSummaries"
          show-summary
          border
          stripe
          @select="handleSelectionChange"
          @select-all="handleSelectionAllChange"
          @selection-change="selectionChangeFn"
        >
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column label="订单时间" align="center"  width="160">
            <template slot-scope="scope">
              <span>{{scope.row.orderDate|dateFormatter}}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单号" align="center" prop="orderSn" width="180" />
          <el-table-column label="应收金额" align="center" prop="amount" width="120" />
          <el-table-column label="已收金额" align="center" prop="amountPaid" width="120" />
          <el-table-column label="未收金额" align="center" prop="restAmount" width="120" />
          <el-table-column label="本次收款" align="center" prop="submitAmount" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.submitAmount" type="number" @input="scope.row.submitAmount = submitAmountInput($event,scope.$index)"></el-input>
            </template>
          </el-table-column>
          <!--<el-table-column label="水票" align="center" prop="quantity" width="100" v-if="form.paymentPluginId == 'paperPayPlugin'">-->
            <!--<template slot-scope="scope">-->
              <!--<el-input v-model="scope.row.quantity" type="number"></el-input>-->
            <!--</template>-->
          <!--</el-table-column>-->
          <el-table-column label="说明" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.memo"></el-input>
            </template>
          </el-table-column>
        </el-table>
                <div style="display: flex;justify-content: space-between;">
                  <div style="margin-top: 20px;">
                    <!--<span style="font-size: 16px;color: red;">对账金额：{{unpayAmount}}</span>-->
                  </div>
                  <div style="margin-top: 20px;">
                    <el-button v-permission="['receivable.add']" type="primary" :loading="saveClicked" @click="saveClick" :disabled="selectionChange.length===0">确 定</el-button>
                  </div>
                </div>
        </div>
      </el-form>
    </el-main>


    <el-dialog
      title="双击选择对账单"
      :visible.sync="verifyTableVisible"
      width="950px"
      v-el-drag-dialog
      append-to-body
      :before-close="verifyTableClose">
      <div style="position: relative;">
        <verify-table :key="times"  :verifyType="form.type" @verifyDbClick="verifyDouble" @verifyTableClose="verifyTableClose"></verify-table>
      </div>
    </el-dialog>
  </el-container>
</template>
<script>
  import {EventBus} from '@/api/eventBus'
  import verifyTable from '@/components/Verify/index'
  import memberTable from '@/components/MemberTable/index'
  import loadMore from '@/utils/loadMore.js'
  import { list as receivableList } from '@/api/receivable'
  import { list as memberList } from '@/api/member'
  import {list as sysEmployeelist} from '../../api/sysEmployee'
  import { save } from '@/api/payment'
  import Pagination from '@/components/Pagination'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import utils from '../../utils/utils.js'
  import ElRow from "element-ui/packages/row/src/row";
//  import ElTableFooter from "element-ui/packages/table/src/table-footer";
  export default {
    name: 'receivable-add',
    directives: { loadMore, permission ,elDragDialog},
    components: {
//      ElTableFooter,
      ElRow,
      Pagination,memberTable,verifyTable },
    filters: {
      watchStatus(val) {
        if (val === 0 || val === 1) {
          return '待收款'
        } else if (val === 1) {
          return '部份收款'
        } else if (val === 2) {
          return '已完成'
        }
      },
      watchOrderType (val) {
        if (val == 0) {
          return '销售单'
        } else if (val == 1) {
          return '退货单'
        }
      }
    },
    data() {
      return {
        receivableMemberList: [],
        queryType: true,
        total: 0,
        times:'',
        pageNum: 1,
        memberVisible:false,
        verifyTableVisible: false,
        pageSize: 20,
        memberName: '',
        isWaterShow: false,
        statusOptions: [
          { label: '全部', value: '' },
          { label: '待付款', value: 0 },
          // { label: '部份付款', value: 1 },
          { label: '已完成', value: 2 }
        ],
        paymentOptions: [
          { label: '现金', value: 'cashPayPlugin' },
          { label: '转账', value: 'debtPayPlugin' }
        ],
        paymentPluginName: '',
        maxAmount: 0,
        unpayAmount: 0,
        collectAmount: '',
        form: {
          memberId: null,
          paymentPluginId: '',
          type: 0,
          memo: '',
          sn: '',
          orderDate: '',
          verifyId: null,
          itemList: [],
          managerId:''
        },
        memberList: [],
        selectionChange: [],
        itemList: [],
        saveClicked: false,
        curHeight: null,
        pickerOptions: {// 时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        sysEmployeelistobtain:[],
         //payee:'',
         //id:null
      }
    },
    created() {
      this.loadMember("");
      this.sysEmployeelist()
      if(this.$route.query.memberId!=null){
        this.form.paymentPluginId=this.$route.query.paymentPluginId;
        this.paymentPluginName=this.$route.query.paymentPluginName
        this.form.memberId=this.$route.query.memberId
        this.memberName=this.$route.query.memberName
       // this.id=this.$route.query.id
        this.loadReceivable(this.form.memberId)
      }
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    methods: {
      sysEmployeelist(){
        sysEmployeelist().then(res=>{
           this.sysEmployeelistobtain=res.data.data
        })
      },
      doubleSupplier(data){
        this.memberName=data.name
        this.form.memberId=data.id
        this.memberVisible=false
      },
      toSearchMember(){
        this.times=new Date().getSeconds()
        this.memberVisible=true
      },
      loadReceivable(id) {//debugger
        const params = new URLSearchParams()
        params.append('pageNum', this.pageNum)
        params.append('pageSize', this.pageSize)
        if (this.form.memberId != null && this.form.memberId != 'undefined')
          params.append('memberId', this.form.memberId)
        if (this.form.verifyId != null && this.form.verifyId != 'undefined')
          params.append('verifyId', this.form.verifyId);
        params.append('status', 0)
        this.maxAmount = 0
        receivableList(params).then(res => {
          this.receivableMemberList = res.data.data.map(item => {
            item.amount = Number(item.amount).toFixed(2)
            item.amountPaid = Number(item.amountPaid).toFixed(2)
            item.restAmount = (item.amount - item.amountPaid).toFixed(2)
            item.submitAmount = ''
            this.maxAmount += Number(item.restAmount)
            return item
          })
          const index = this.receivableMemberList.findIndex(item => { return item.id === id })
          index !== -1 && this.$nextTick(() => {
            this.$refs.receivableMemberTable.toggleRowSelection(this.receivableMemberList[index])
            this.receivableMemberList[index].submitAmount = this.receivableMemberList[index].restAmount
          })
        }).catch(err => { console.log(err) })
      },
      selectionChangeFn(data) {
        this.selectionChange = data
      },
      handleSelectionChange(data) {
        this.selectionChange = data;
        this.unpayAmount = 0;
        this.selectionChange.forEach(item1 => {
          this.unpayAmount = this.unpayAmount + (Number(item1.amount) - Number(item1.amountPaid));
          const index = this.receivableMemberList.findIndex(item2 => {
            return item1.id === item2.id && (item2.submitAmount === '' || item2.submitAmount === '0.00')
          })
          if (index !== -1) {
            this.receivableMemberList[index].submitAmount = this.receivableMemberList[index].restAmount
          }
        })
        this.unpayAmount = this.unpayAmount.toFixed(2);
      },
      handleSelectionAllChange(data) {
        this.selectionChange = data;
        this.unpayAmount = 0;
        this.selectionChange.forEach(item1 => {
          this.unpayAmount = this.unpayAmount + (Number(item1.amount) - Number(item1.amountPaid));
        });
        this.unpayAmount = this.unpayAmount.toFixed(2);
        this.receivableMemberList.forEach(item => {
          if (item.submitAmount !== '' || item.submitAmount !== '0.00') {
            item.submitAmount = item.restAmount
          }
        })
      },
      saveClick() {
        var _this = this
        if (this.selectionChange.length === 0) {
          this.$message({ message: '应收账款不能为空', type: 'warning' })
        } else {
          this.saveClicked = true
          const data = []
          console.log(this.selectionChange);
          try {
            this.selectionChange.forEach(item => {
              if (Number(item.submitAmount) <= 0) {
                throw new Error()
              }
              const obj = {
                amount: item.submitAmount,
                createDate: item.createDate,
                receivableId: item.id,
                enterpriseId: item.enterpriseId,
                memberId: item.memberId,
                paymentPluginId: this.form.paymentPluginId,
                paymentPluginName: this.paymentPluginName,
                //managerId:this.form.managerId,
                employeeId:this.form.managerId,
                memo: item.memo,
                refund: 0,
                way: 1,
                quantity:item.quantity
              }
              //传递给后台，更新对账单的状态
              if (this.form.verifyId != '' && this.form.verifyId != 'undefined'){
                obj.verifyId = this.form.verifyId;
              }
              data.push(obj)
            })
          } catch (e) {
            this.$message({ message: '本次收款不能为空', type: 'warning' })
            this.saveClicked = false
            return
          }
          data.forEach(function(item){
            console.log(item)
            item.quantity = 0
          })
          save(data).then(res => {
            /*this.loadReceivable().then(() => {
              this.closeDialog()
              this.saveClicked = false
            })*/
            if (res.type == 'success'){
              this.$message({ message: '收款成功', type: 'success' });

              EventBus.$emit('receivable-add', res.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/receivable/list'
                })
              })

            }
          }).catch(() => { this.saveClicked = false })
        }
      },
      closeDialog() {
        this.collectAmount = ''
        this.maxAmount = ''
        this.receivableMemberList = []
        this.selectionChange = []
        if (this.selectionChange.length !== 0) {
          this.$refs.receivableMemberTable.clearSelection()
        }
        this.dialogVisible = false
      },
      getSummaries(param) {
        this.$nextTick(() => {
          this.$refs.receivableMemberTable.doLayout()
        })
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价'
            return
          }
          if (index === 2){
            return;
          }
          const values = data.map(item => Number(item[column.property]))
          console.log("48574685685466835748644");

        console.log(values);
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return (Number(prev) + Number(curr)).toFixed(2)
              } else {
                return prev
              }
            }, 0)
            sums[index] += ' 元'
          }
        })

        return sums
      },

      beforeMount() {
        window.onresize = () => {
          return (() => {
            const h = document.documentElement.clientHeight || document.body.clientHeight
            if (this.queryType === false) {
              this.curHeight = h - 266// 减去页面上固定高度height
            } else {
              this.curHeight = h - 220// 减去页面上固定高度height
            }
          })()
        }
      },
      comeIn() {
        const h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220// 减去页面上固定高度height
      },
      chooseClick() {
        this.queryType = !this.queryType
        const h = document.documentElement.clientHeight || document.body.clientHeight
        if (this.queryType === false) {
          this.curHeight = h - 266// 减去页面上固定高度height
        } else {
          this.curHeight = h - 220// 减去页面上固定高度height
        }
      },
      selectMember(val){
        if(val == '#'){
          this.form.supplierId = '';
          this.memberVisible = true;
        }
        this.memberName=val.name;
        this.form.memberId=val.id;
        this.loadReceivable("");
      },
      remoteMethod(query) {
        this.loadMember(query)
      },
      loadMember(query) {
        let params = new URLSearchParams()
        params.append('name', query)
        memberList(params).then(res => {
          this.memberList = res.data.data
        })
      },
      paymentChange(value) {
        this.form.paymentPluginId = value
        const item = this.paymentOptions.find(val => { return val.value === value })
        this.paymentPluginName = item.label
      },
      collectAmountInput() { // 批量添加本次收款
        if (this.collectAmount <= 0) {
          // this.$message({ message: '收款金额不能小于1' })
          this.$refs.receivableMemberTable.clearSelection()
          this.collectAmount = ''
        } else if (this.collectAmount > this.maxAmount) {
          this.collectAmount = Number(this.maxAmount).toFixed(2)
        }
        let content = this.collectAmount
        this.$refs.receivableMemberTable.clearSelection()
        this.receivableMemberList.forEach((item, index) => {
          item.submitAmount = content - item.restAmount >= 0 ? Number(item.restAmount).toFixed(2) : Number(content).toFixed(2)
          if (item.submitAmount > 0) { // 本次收款大于0则勾选
            this.$refs.receivableMemberTable.toggleRowSelection(this.receivableMemberList[index])
          } else {
            item.submitAmount = ''
          }
          content -= item.restAmount
          content = content >= 0 ? content : 0 // 防止负数
        })
      },
      allReceivable() {
        this.$refs.receivableMemberTable.clearSelection()
        this.collectAmount = ''
        this.receivableMemberList.forEach((item, index) => {
          item.submitAmount = item.restAmount
          this.$refs.receivableMemberTable.toggleRowSelection(this.receivableMemberList[index])
        })
      },
      submitAmountInput(value, index) { // 限制本次收款不超过未收金额
        const item = this.selectionChange.find(val => {
          return val.id === this.receivableMemberList[index].id
        })
        item === undefined && this.$refs.receivableMemberTable.toggleRowSelection(this.receivableMemberList[index])
        if (Number(value) > Number(this.receivableMemberList[index].restAmount)) {
          return this.receivableMemberList[index].restAmount
        } else if (Number(value) <= 0) {
          // 执行两次表示去除勾选
          this.$refs.receivableMemberTable.toggleRowSelection(this.receivableMemberList[index])
          return ''
        } else {
          return value
        }
      },
      verifyDouble(data){
        this.form.verifyId = data.id;
        this.form.sn = data.sn;
        this.verifyTableVisible = false;
        this.loadReceivable("");
      },
      verifyTableClose(){
        this.verifyTableVisible = false
      },
      verifyDialogShow() {
        this.verifyTableVisible = true;
      },
    }
  }
</script>

<style scoped>

  body .el-table th.gutter {
    display: table-cell !important
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    height: 40px
  }
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
          padding: 10px;
          /* height: 100% !important; */
          padding-bottom: 0;
        }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
  .report_body{
    padding-top: 10px;
    padding-bottom: 10px;
    margin-top: 5px;
  }
  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 20px;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
</style>
